package com.activities;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.Adapters.SpinnerAdapter;
import com.Adapters.UploadAdapter;
import com.Adapters.Items.ActionsUpload;
import com.Adapters.Items.ItemPost;
import com.Adapters.Items.ItemUpload;
import com.Animations.AnimUtil;
import com.Data.Albums;
import com.Data.Post;
import com.Data.User;
import com.Dialogs.DialogManagerClass;
import com.Dialogs.DialogManagerClass.onCommentChange;
import com.Dialogs.DialogManagerClass.onTagChange;
import com.Location.PictureLocation;
import com.Managers.DirManagerClass;
import com.Managers.FragmentManagerClass;
import com.Managers.PictureIntentManagerClass;
import com.Managers.UserManagerClass;
import com.SoapClasses.SoapUtil;
import com.TextFormat.UtilFonts;
import com.UploadClasses.UploadManager;
import com.shareup.R;
import com.utils.AppConstant;
import com.utils.Utils;


public class ActivityUpload extends Activity implements ActionsUpload {

    public static final int CROP_PIC = 150;

    public static ArrayList<String[]> dataToSend;

    public static int IDOWNER;

    public static final int MULTIPLE = 200;

    public static final int SELECT_ALBUM = 300;

    public static final int SELECT_PHOTO = 100;

    public final String REQUESTED_IMAGEURL = "IMAGE";

    private UploadAdapter adapter;

    private ImageButton addComment;

    private ImageButton addLocation;

    private ImageButton addTag;

    private int albumCover = 0;

    private int albumIndex = 0;

    private String albumName;

    private final boolean cameFromLogin = false;

    private final OnClickListener clickAlbum = new OnClickListener() {

        @Override
        public void onClick(View v) {

            showSelectAlbum();
        }

    };

    private final OnClickListener ClickClose = new OnClickListener() {

        @Override
        public void onClick(View v) {

            exit();
        }
    };

    private final OnItemSelectedListener ClickPrivacy = new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> adapt, View arg1, int pos, long arg3) {

            String item = data.get(pos).get("id");
            Log.e("privacy", item);
            privacyIndex = Integer.parseInt(item);

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {

            // TODO Auto-generated method stub

        }
    };

    private ImageView closeImage;

    private int columnWidth;

    private String comment = "";

    private List<Map<String, String>> data;

    private ImageButton doneButton;

    private GridView gridView;

    private String[] pictureList;

    private int privacyIndex = 1;

    private ImageView selectAlbum;

    private TextView sharealbumnametext;

    private Spinner sharewith;

    private String tag = "";

    private TextView title;

    public void askForImage() {

        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();
        //
        if (Intent.ACTION_SEND.equals(action) && type != null) {
            if (type.startsWith("image/")) {
                PictureIntentManagerClass.startIntentForCrop(true, intent, this);
            }
        }
        else
            if (Intent.ACTION_SEND_MULTIPLE.equals(action)
                        && type != null) {
                PictureIntentManagerClass.startIntentForCrop(true, intent, this);
                pictureList = PictureIntentManagerClass.pictures;

                if (pictureList != null && pictureList.length > 1)
                    continueImage(UserManagerClass.UserLogged.getID());
            }
            else {
                continueImage(UserManagerClass.UserLogged.getID());
            }
    }

    public void CallBackFromUpload() {

        exit();
    }

    @Override
    public Integer getAlbumId() {

        return albumIndex;
    }

    public void Init() {

        sharewith = (Spinner) findViewById(R.id.sp_shared);

        //
        title = (TextView) findViewById(R.id.title_actionbar);
        TextView sharetext = (TextView) findViewById(R.id.sharewith_text);
        TextView sharealbumtext = (TextView) findViewById(R.id.sharewith_album_text);
        sharealbumnametext = (TextView) findViewById(R.id.sharewith_album_name);
        UtilFonts.setTextBoldFont(title);
        UtilFonts.setTextRegularFont(sharetext, sharealbumtext, sharealbumnametext);
        //
        selectAlbum = (ImageView) findViewById(R.id.album_select);
        selectAlbum.setOnClickListener(clickAlbum);
        //
        doneButton = (ImageButton) findViewById(R.id.button_done);
        //
        sharewith.setSelection(1);
        //
        closeImage = (ImageView) findViewById(R.id.button_back);
        gridView = (GridView) findViewById(R.id.list_thumb);
        //
        closeImage.setOnClickListener(ClickClose);
        //
        addComment = (ImageButton) findViewById(R.id.acrop_add_comment);
        addComment.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                dialogShowComment();
            }
        });
        addTag = (ImageButton) findViewById(R.id.acrop_add_tags);
        addTag.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                dialogShowTag();
            }
        });
        addLocation = (ImageButton) findViewById(R.id.acrop_add_location);
        addLocation.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                dialogShowLocation();
            }
        });
        addPrivacy();
        //

        this.albumName = SoapUtil.ALBUM_NAME;
        this.albumIndex = SoapUtil.ALBUM_ID;

        if (this.albumName != null && !this.albumName.equals(""))
            sharealbumnametext.setText(this.albumName);
        //
        askForImage();
        //
        updateLocation();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            //
            return true;
        }
        //
        return super.onKeyUp(keyCode, event);
    }

    /*
     * (non-Javadoc)
     * @see
     * com.Adapters.Items.ActionsUpload#remove(com.Adapters.Items.ItemUpload)
     */
    @Override
    public void remove(ItemUpload object) {

        int index = adapter.removeItem(object.getItemup());
        pictureList[index] = null;

        index--;

        if (index < 0)
            index = 0;

        if (adapter.getCount() == 0)
            exit();
        else
            adapter.getItem(index).setCover(true);

    }

    /*
     * (non-Javadoc)
     * @see
     * com.Adapters.Items.ActionsUpload#setAsCover(com.Adapters.Items.ItemUpload
     * )
     */
    @Override
    public void setAsCover(int id) {

        for (ItemPost pp : adapter.getRows()) {
            if (pp.getPostId() != id)
                ((ItemUpload) pp).removeAsCover();
        }

    }

    private void addPrivacy() {

        String[] array = getResources().getStringArray(R.array.picture_shared_with);
        int cont = 0;
        data = new ArrayList<Map<String, String>>();
        for (String s : array) {
            Map<String, String> datum = new HashMap<String, String>(2);
            datum.put("id", String.valueOf(cont));
            datum.put("name", s);
            data.add(datum);
            cont++;
        }
        SpinnerAdapter adapter = new SpinnerAdapter(this, data, R.layout.item_dropdown_spinner, new String[] {
                    "name", "id" }, new int[] { android.R.id.text1 });

        sharewith.setAdapter(adapter);
        sharewith.setOnItemSelectedListener(ClickPrivacy);
        sharewith.setSelection(1);

    }

    private void changeCover() {

        if (albumCover == 0 && albumIndex > 0)
            adapter.getUploadItem(0).setAsCover();

        if (albumName == null || albumName.equals(""))
            albumName = getResources().getString(R.string.crop_to_album_no_album_selected);
        sharealbumnametext.setText(albumName);
    }

    private void continueImage(final int id) {

        // IF ITS ONLY ONE PICTURE TO UPLOAD
        if (pictureList == null)
            pictureList = new String[] { DirManagerClass.getNameCutPicture() };

        this.InitilizeGridLayout();

        adapter = new UploadAdapter(this, R.layout.item_album, columnWidth, this);
        //
        int index = 0;
        for (String path : pictureList) {
            Post p = new Post();
            p.setPathFull(path);
            p.setID(index);
            adapter.add(p);
            index++;

        }

        gridView.setAdapter(adapter);

        doneButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                uploadImages();
            }
        });
    }

    private void dialogShowComment() {

        DialogManagerClass.showAddCommentDialog(this, comment, new onCommentChange() {

            @Override
            public void Changed(String text) {

                comment = text;

            }
        });

    }

    private void dialogShowLocation() {

        DialogManagerClass.showShareLocationDialog(this);
    }

    private void dialogShowTag() {

        DialogManagerClass.showAddTagDialog(this, tag, new onTagChange() {

            @Override
            public void Changed(String text) {

                tag = text;

            }
        });
    }

    private void exit() {

        SoapUtil.ALBUM_ID = 0;
        SoapUtil.ALBUM_NAME = "";

        if (cameFromLogin)
            FragmentManagerClass.aMain.finish();

        finish();
        AnimUtil.getActivityTransition(this, false);
    }

    private void gotoLogin() {

        Intent intent = new Intent(this, ActivityVerifyLogin.class);
        startActivity(intent);
        AnimUtil.getActivityTransition(this, true);
        //
        finish();
    }

    private void InitilizeGridLayout() {

        Resources r = getResources();
        float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, AppConstant.GRID_PADDING, r.getDisplayMetrics());

        Utils utils = new Utils(this);

        if (pictureList.length > 1) {

            columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
            gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS_UPLOAD);
            gridView.setColumnWidth(columnWidth);
            gridView.setStretchMode(GridView.NO_STRETCH);
            gridView.setHorizontalSpacing((int) padding);
            gridView.setVerticalSpacing((int) padding);
        }
        else {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) gridView.getLayoutParams();
            params.height = LayoutParams.WRAP_CONTENT;
            params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
            gridView.setLayoutParams(params);
            gridView.setNumColumns(1);
            gridView.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
        }
        gridView.setPadding((int) padding, (int) padding, (int) padding, (int) padding);

    }

    private void showSelectAlbum() {

        Intent intent = new Intent(this, ActivityAlbums.class);
        startActivityForResult(intent, SELECT_ALBUM);
        AnimUtil.getActivityTransition(this, true);

    }

    private void updateLocation() {

        if (UserManagerClass.UserLocation == null) {
            PictureLocation pl = new PictureLocation();
            pl.updateGeoUserLocation(this);
        }

    }

    private void uploadImages() {

        // IF WE HAVE AN USER LOGGED
        if (UserManagerClass.UserLogged != null
                    && UserManagerClass.UserLogged.getID() > 0) {

            ItemUpload[] uploads = new ItemUpload[adapter.getCount()];
            for (int i = 0; i < uploads.length; i++) {

                uploads[i] = adapter.getUploadItem(i);
            }
            Post data = new Post();
            Albums al = new Albums();
            al.setID(albumIndex);
            User owner = new User();
            owner.setID(IDOWNER);
            data.setComment(comment);
            data.setTags(tag);
            data.setAlbum(al);
            data.setUser(owner);
            data.setPrivate(privacyIndex);
            new UploadManager().UploadPicture(this, data, uploads);

            exit();
        }// END IF USER

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == CROP_PIC) {
            if (resultCode == RESULT_OK) {
                continueImage(UserManagerClass.UserLogged.getID());
            }
            else {
                exit();
            }
        }
        else
            if (requestCode == MULTIPLE) {
                if (resultCode == RESULT_OK)
                    continueImage(UserManagerClass.UserLogged.getID());

            }
            else
                if (requestCode == SELECT_ALBUM) {
                    if (resultCode == RESULT_OK) {
                        albumIndex = data.getIntExtra("ALBUM_ID", 0);
                        albumCover = Integer.parseInt(data.getStringExtra("ALBUM_COVER"));
                        albumName = data.getStringExtra("albumName");
                        changeCover();
                    }

                }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.activity_upload);
        super.onCreate(savedInstanceState);

        if (UserManagerClass.UserLogged == null)
            UserManagerClass.UserLogged = new UserManagerClass(this).getInfo();

        if (UserManagerClass.UserLogged.getID() == 0) {
            gotoLogin();
        }
        Init();
    }

}
